package com.aglhz.nature.presenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.util.Log;

import com.aglhz.nature.constants.ServerAPI;
import com.aglhz.nature.events.MyselfViewEvent;
import com.aglhz.nature.events.SetViewEvent;
import com.aglhz.nature.modle.CodeBean;
import com.aglhz.nature.modle.WXUserInfo;
import com.aglhz.nature.modle.other.Other;
import com.aglhz.nature.presenter.base.BasePresenter;
import com.aglhz.nature.view.iv.MyselfView;
import com.aglhz.nature.view.iv.SetView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

public class SetPresenter extends BasePresenter{
	
	private static String TAG = SetPresenter.class.getName();
	
	// view
		private SetView setView;
		//data
		private CodeBean codeBean;
		public SetPresenter(SetView view) {
			super();
			setView = view;
		}
		
		public void logOut(){
			String url=ServerAPI.APIHEARD+ServerAPI.LOGOUT;
			
			AsyncHttpClient client = new AsyncHttpClient();
			client.post(url, new TextHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode,
						cz.msebera.android.httpclient.Header[] headers,
						String responseString) {
					try {
						Log.e(TAG, "response" + responseString);

						Gson gson = new Gson();

						CodeBean coBean = gson.fromJson(responseString,
								CodeBean.class);	
						
						Log.e("------Other other---------------",
								"--------other---------------" + coBean);
						codeBean = (CodeBean)coBean.clone();
						int code = Integer.parseInt(codeBean.getOther().getCode());
						if (code == 200) {											
							Log.e("------code == 200--------------",
									"--------code == 200--------------" );
							// send event
							SetViewEvent event = new SetViewEvent(
									SetViewEvent.EVENT_LOGOUT_VIEW);
							EventBus.getDefault().post(event);

						} else {

						}

						Log.e(TAG, "success" + "success");
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(int statusCode,
						cz.msebera.android.httpclient.Header[] headers,
						String responseString, Throwable throwable) {

					Log.e(TAG, "failure");
				}

			});

		}
		
		// /*********************view operation*******************///
		@Subscribe(threadMode = ThreadMode.MAIN)
		public void onEventSetViewThread(SetViewEvent event) {
			Log.e("------EVENT_LOGOUT_VIEW---------------","qqqqqqqqqqqqqqqqqq");
			String msg = event.getMessage();
			Log.i(TAG, "onEventSetViewThread:" + msg);
			// update UI By event
			if (SetViewEvent.EVENT_LOGOUT_VIEW == msg) {
				// update  view
				Log.e("------EVENT_LOGOUT_VIEW---------------","vvvvvvvvvvvvvvvvvvv");
			setView.ClearUserInfo();
			setView.changeToLogIn();
			}

		}
}
